package models

import (
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
	"gorm.io/gorm"
)

// MerchantRelation 商户与代理关系表
type MerchantRelation struct {
	Model
	MerchantID int    `gorm:"column:merchant_id;not null" json:"merchant_id"` // 商户ID
	AgentID    int    `gorm:"column:agent_id;not null" json:"agent_id"`       // 代理商ID
	Relation   string `json:"relation" gorm:"comment:'代理关系 逗号隔开'"`
}

// MerchantRelationGetInfoByMerchantId 通过id获取详情
func MerchantRelationGetInfoByMerchantId(merchantId interface{}) (map[string]string, error) {
	merchantRelation := new(MerchantRelation)
	err := db.Model(&MerchantRelation{}).Where("merchant_id = ?", merchantId).Scan(&merchantRelation).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Error("商户关系不存在: merchantId:%d err:%v", merchantId, err)
		return nil, fmt.Errorf("商户关系不存在")
	}
	if merchantRelation.ID == 0 {
		logrus.WithError(err).Errorf("商户关系不存在 merchantId: %s", merchantId)
		return nil, errors.New("商户关系不存在")
	}

	return map[string]string{
		"merchantId": cast.ToString(merchantRelation.MerchantID),
		"agentId":    cast.ToString(merchantRelation.AgentID),
		"relation":   merchantRelation.Relation,
	}, nil
}

// MerchantRelationAdd 添加
func MerchantRelationAdd(merchantId, agentId interface{}, relation string) error {
	agentRelation := &MerchantRelation{
		MerchantID: cast.ToInt(merchantId),
		AgentID:    cast.ToInt(agentId),
		Relation:   relation,
	}
	err := db.Create(agentRelation).Error

	if err != nil {
		logrus.WithError(err).Infof("商户关系添加失败: merchantId:%s agentId:%s relation:%s", merchantId, agentId, relation)
		return fmt.Errorf("商户关系添加失败")
	}

	return nil
}
